#include "CStlFile.h"

CStlFile::CStlFile():m_stream(NULL)
{}

CStlFile::~CStlFile()
{
	Close();
}

bool CStlFile::Open(const char* filename,const char *mode)
{
	assert(filename!=NULL);
	Close();
	m_stream = fopen(filename,mode);
	return (m_stream!=NULL);
}

int CStlFile::Read(void *buffer,unsigned int count)
{
	assert(m_stream!=NULL);
	return fread(buffer,1,count,m_stream);
}

int CStlFile::Write(const void *buffer,unsigned int count)
{
	assert(m_stream!=NULL);
	return fwrite(buffer,1,count,m_stream);
}
void CStlFile::Close()
{
	if (m_stream!=NULL)
	{
		fclose(m_stream);
		m_stream = NULL;
	}
}
bool CStlFile::GetLine(char *str,int n)
{
	 assert(str!=NULL);
	 assert(m_stream!=NULL);
	 return (fgets(str,n,m_stream)!=NULL);
}
long CStlFile::Seek(long offset,int origin)
{
	assert(m_stream!=NULL);
	return fseek(m_stream,offset,origin);
}

long CStlFile::Tell()
{
	assert(m_stream!=NULL);
	return ftell(m_stream);
}
bool CStlFile::Flush()
{
	assert(m_stream!=NULL);
	return (fflush(m_stream)==0);
}

long CStlFile::GetLength()
{
	assert(m_stream!=NULL);
	long lcurrent = fseek(m_stream,0,SEEK_END);
	return fseek(m_stream,lcurrent,SEEK_SET);
}
long CStlFile::GetLength(const char* filename)
{
	struct stat f_stat;
	if (stat(filename, &f_stat) == -1) {
		return -1;
	}
	return (long)f_stat.st_size;
}

bool CStlFile::Setlength(int len)
{
	assert(m_stream!=NULL);
#ifdef WIN32
	return ::SetEndOfFile((HANDLE)::_get_osfhandle(fileno(m_stream)));
#else
	return (ftruncate(fileno(m_stream),len) == 0);
#endif
} 

bool CStlFile::IsOpened()
{
	return (m_stream!=NULL);
}

bool CStlFile::Eof()
{
	assert(m_stream!=NULL);
	return feof(m_stream);
}